import json

from django.forms import model_to_dict

from django import forms
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from app01 import models

from datetime import datetime
from app01.utils.pagination import pagination


class TeamModelForm(forms.Form):
    team_name = forms.CharField(error_messages={'required': '请输入团队名称'})

    def clean_team_name(self):
        team_name = self.cleaned_data.get('team_name')
        # 判断名称是否已存在
        if models.Team.objects.filter(team_name=team_name).exists():
            self.add_error('team_name', '团队名称已存在')
            return self.cleaned_data
        self.cleaned_data['team_name'] = team_name
        return self.cleaned_data


def team_list(request):
    queryset = models.TeamUser.objects.all().order_by('team')
    page_obj = pagination(request, queryset)
    form = TeamModelForm()
    context = {
        'form': form,
        'queryset': page_obj.page_queryset,  # 分页后的数据
        'page_string': page_obj.html(),  # 生成页码
    }
    user_name = request.tracer.user.get('name')
    return render(request, 'team_list_vue.html', locals())


def team_post(request):
    # 返回所有数据

    if request.method == 'GET':

        # 获得所有团队和所有成员
        staff_list = models.StaffInfo.objects.all().order_by('team_id')
        staff_list = list(staff_list.values())
        # print('team_list', team_list)
        """
        {'id': '1',
             'team_name': '销售部',
             'team_leader': '张三',
             'team_leader_phone': '12345678901',
             'team_leader_email':' '},
        """
        team_content_list = []
        team_name = []
        for i in staff_list:
            grade = i['level']
            team_id = i['team_id']
            if not team_id:
                team_name = '无团队'
            else:
                team_name = models.Team.objects.filter(id=team_id).values('name')
                team_name = team_name[0]['name']
            team_content_list.append(
                {'id': i['staff_num'],
                 'team_name': team_name,
                 'member_name': i['name'],
                 'member_grade': models.StaffInfo.level_choices[grade - 1][1],
                 'customer_count': i['customer_count'],
                 })

        # 获得未在Teamuser表里的员工列表，
        # 1.获得所有员工列表
        staff_list = models.StaffInfo.objects.all().order_by('id')

        staff_list = list(staff_list.values())
        # print('staff_list', staff_list)

        # 2.获得StaffInfo中，team值为空的成员
        # 4.获得未在Teamuser表里的员工列表
        staff_list_new = models.StaffInfo.objects.filter(team_id=None).order_by('id')
        staff_list_new = list(staff_list_new.values())

        # print('staff_list_new', staff_list_new)

        # #获得当前登录人的信息
        # info=request.tracer.user
        # print('info',info)
        user_num = request.tracer.user.get('id')

        user_info = models.StaffInfo.objects.filter(staff_num=user_num).first()

        team_all_list = models.Team.objects.all().order_by('id')
        team_all_list = list(team_all_list.values())

        team_choice_list = []
        for i in team_all_list:
            team_choice_list.append({'id': i['id'], 'name': i['name']})

        level_choice = models.StaffInfo.level_choices
        level_choice_list = []
        for i in level_choice:
            level_choice_list.append({'id': i[0], 'name': i[1]})

        if not user_info:
            return HttpResponse('请求错误，请重新登录')
        else:
            create_team_list = {
                'team_name': '',
                'id': user_info.id,
                'member_name': user_info.name,
                'member_grade': user_info.level_choices[1][1],
                'customer_count': user_info.customer_count,
                'customer_count_contract': user_info.customer_count_contract,
                'customer_percent': user_info.percent,
                'create_time': datetime.now().strftime('%Y-%m-%d'),
            }
        member_grade = user_info.level

        return JsonResponse(
            {'code': 200, 'data': team_content_list, 'staff_list': staff_list_new,
             'create_team_list': create_team_list, 'member_grade': member_grade, 'team_all_list': team_all_list
                , 'team_choice_list': team_choice_list, 'level_choice_list': level_choice_list})
    # 添加数据
    if request.method == 'POST':
        # 获取后台axios请求发送来的数据content

        team_message = request.body.decode('utf-8')
        # 将数据json转换成字典
        team_message = json.loads(team_message)

        # 获取数据
        team_name = team_message.get('team_name')
        # 判断团队名称是否已存在
        if models.Team.objects.filter(name=team_name).exists():
            return JsonResponse({'code': 400, 'msg': '团队名称已存在'})

        team_obj = models.Team.objects.create(name=team_name)
        if not team_obj:
            return JsonResponse({'code': 400, 'msg': '团队创建失败'})

        return JsonResponse({'code': 200, 'msg': '团队创建成功'})


def team_delete(request):
    # 删除数据
    if request.method == 'POST':

        # 获取axios请求发送来的数据
        user_message = request.body.decode('utf-8')
        # 将数据json转换成字典
        user_message = json.loads(user_message)
        # 获取数据
        user_num = user_message.get('id')
        # 删除数据
        print('user_num2', user_num)
        # 获取该user_num的对象
        user_obj = models.StaffInfo.objects.filter(staff_num=user_num).first()
        print('user_obj', user_obj)
        if not user_obj:
            return JsonResponse({'code': 400, 'msg': '该成员不存在'})
        # 将该成员所负责的客户的staff_id置为空
        # 查询该员工负责的客户
        customer_obj = models.CustomerList.objects.filter(staff_id=user_obj.id)
        # 获取工号为187377的员工
        print('customer_obj', customer_obj)
        admin_id = models.StaffInfo.objects.filter(staff_num='187377').first().id
        print('admin_id', admin_id)
        if customer_obj:
            customer_obj.update(staff_id=admin_id)
            # id为admin123的员工的客户数加上该员工的客户数
            admin_obj = models.StaffInfo.objects.filter(staff_num='187377').first()
            print('admin_obj', admin_obj)
            admin_obj.customer_count += user_obj.customer_count
            print('admin_obj.customer_count', admin_obj.customer_count)
            admin_obj.financial_product_count += user_obj.financial_product_count
            admin_obj.fund_products_count += user_obj.fund_products_count
            admin_obj.investment_assets_count += user_obj.investment_assets_count
            admin_obj.add_weChat_count += user_obj.add_weChat_count
            admin_obj.contract_stock_count += user_obj.contract_stock_count
            admin_obj.yield_enhanced_products_count += user_obj.yield_enhanced_products_count
            admin_obj.equity_public_offering_count += user_obj.equity_public_offering_count
            admin_obj.small_t_one_assets_count += user_obj.small_t_one_assets_count
            admin_obj.stock_financing_count += user_obj.stock_financing_count
            admin_obj.more_t_one_assets_count += user_obj.more_t_one_assets_count
            admin_obj.Private_equity_products_count += user_obj.Private_equity_products_count
            admin_obj.configure_China_count += user_obj.configure_China_count
            print('asda!')
            admin_obj.save()
        # 删除数据
        user_obj.delete()
        return JsonResponse({'code': 0, 'msg': '删除成功'})


def edit_clean(team_message):
    team_id = models.Team.objects.filter(name=team_message['team_name']).first()
    # 处理数据
    team_message['id'] = int(team_message['id'])
    team_message['team_name'] = team_id


def team_edit(request):
    if request.method == 'POST':
        # 获取后台axios请求发送来的数据content
        team_message = request.body.decode('utf-8')
        # 将数据json转换成字典
        team_message = json.loads(team_message)

        """
        {'content': {'id': '1904969', 'team_name': '厦门团队', 'member_name': '廖皓宇', 'member_grade': '团队长', 'customer_count': 1}}
    
        """
        # 获取数据
        team_message = team_message['content']
        print('team_messagedsa', team_message['member_grade'])
        # 修改该员工的team_id
        team_id = models.Team.objects.filter(name=team_message['team_name']).first().id
        # 由member_grade获取level

        judge = models.StaffInfo.objects.filter(staff_num=team_message['id']).update(team_id=team_id,
                                                                                     level=team_message['member_grade'])
        if not judge:
            return JsonResponse({'code': 400, 'msg': '修改失败'})

        return JsonResponse({'code': 0, 'msg': '团队名称修改成功'})
